const express = require("express");
const swig = require("swig");
const mongoose = require("mongoose");
const cookies = require("cookies");

const apiRouter = require("./routers/buyer/apiRouter");
const htmlRouter = require("./routers/buyer/htmlRouter");


new Promise((resolve,reject)=>{
    //连接数据库
    mongoose.connect("mongodb://localhost:27022",(error)=>{
        if(!error){
            console.log("数据库连接成功");
            resolve();
        }else{
            console.log("数据库连接失败");
        }
    })
})
.then(
    ()=>{
        //创建服务器
        const server = express();

        //处理静态资源文件
        server.use("/static",express.static(__dirname+"/public"));
        server.use("/tmp",express.static(__dirname+"/tmp"));
        
        //创建一个cookies对象，挂靠在response上
        server.use((request,response,next)=>{
            let cookie = new cookies(request,response);
            response.cookie = cookie;
            next();
        });

        //处理ajax请求
        server.use("/api",apiRouter);

        //使用模板引擎处理html
        server.engine("html",swig.renderFile);
        server.set("views",__dirname+"/html");
        server.set("view engine","html");
        swig.setDefaults({cache:false});

        server.use("/",htmlRouter);



        //启动服务器
        server.listen(9090,"localhost",(error)=>{
            if(!error){
                console.log("服务器启动成功");
            }else{
                console.log("服务器启动失败");
            }
        })
    }
)